package dyyx.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;


public abstract class FastjsonUtil {

	// SerializerFeature.WriteNonStringKeyAsString
	private static final SerializerFeature[] features = { SerializerFeature.DisableCircularReferenceDetect,
			SerializerFeature.IgnoreErrorGetter, SerializerFeature.WriteNonStringKeyAsString };

	private static final SerializerFeature[] prettyFeatures = getPrettyFeatures();

	private static SerializerFeature[] getPrettyFeatures() {
		int num = features.length;
		SerializerFeature[] arr = new SerializerFeature[num + 1];
		for (int i = 0; i < num; i++) {
			arr[i] = features[i];
		}
		arr[num] = SerializerFeature.PrettyFormat;

		return arr;
	}

	public static String toString(Object obj, boolean pretty) {
		if (obj == null) {
			return null;
		}
		if(obj instanceof String){
			return (String)obj;
		}
		if (pretty) {
			return JSON.toJSONString(obj, prettyFeatures);
		}

		return JSON.toJSONString(obj, features);

	}
	
	
	public static <T> T toObject(String str,Class<T> clazz){
		if(str==null){
			return null;
		}
		if(clazz.equals(String.class)){
			return (T)str;
		}
		
		return JSON.parseObject(str, clazz);
	}
	
	
    public static <T> T toObject(String str, TypeReference<T> valueTypeRef)throws Exception{
    	if(str==null){
			return null;
		}
		return JSON.parseObject(str, valueTypeRef);

    }


}
